package com.yu.waterstation.system.modules.auth;

import com.yu.waterstation.common.common.annotation.NeedPermission;
import com.yu.waterstation.common.common.exception.ServiceException;
import com.yu.waterstation.common.common.util.result.Result;
import com.yu.waterstation.system.common.util.session.SessionUtil;
import com.yu.waterstation.common.entity.system.dto.SysUserDTO;
import com.yu.waterstation.common.entity.system.form.SysUserLoginVO;
import com.yu.waterstation.common.entity.system.form.UpdatePasswordVo;
import com.yu.waterstation.system.modules.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Api(tags = "系统：认证授权")
@RestController
@RequestMapping("/system/auth")
public class AuthController {
    @Resource
    private SysUserService sysUserService;


    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public Result<SysUserDTO> login(@RequestBody SysUserLoginVO sysUserLoginVo,
                                    HttpServletRequest request) throws Exception {
        return Result.ok(sysUserService.login(sysUserLoginVo, request));
    }

    @ApiOperation("退出登录")
    @NeedPermission
    @DeleteMapping("/logout")
    public Result logout(HttpServletRequest request) {
        return Result.ok(SessionUtil.logout(request));
    }

    @ApiOperation("获取登录用户的信息")
    @NeedPermission
    @GetMapping("/userInfo")
    public Result<SysUserDTO> getLoginUserInfo(HttpServletRequest request) throws ServiceException {
        return Result.ok(SessionUtil.getCurrentSysUserDTO(request));
    }

    @ApiOperation("修改密码")
    @NeedPermission
    @PutMapping("/password")
    public Result<Integer> updatePassword(@RequestBody UpdatePasswordVo params, HttpServletRequest request) throws Exception {
        return Result.ok(sysUserService.updatePassword(SessionUtil.getCurrentSysUserId(request), params));
    }


    @ApiOperation("上传头像")
    @NeedPermission
    @PostMapping("/avatar")
    public Result<Integer> uploadUserAvatar(@RequestParam MultipartFile file, HttpServletRequest request) throws ServiceException { // file的名字要和前端input里的name一致
        return Result.ok(sysUserService.updateUserAvatar(file, SessionUtil.getCurrentSysUserDTO(request)));
    }
}